
// WinHomeServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "WinHomeServer.h"
#include "WinHomeServerDlg.h"
#include "BrowseFolderDialog.h"
#include "../LibHttpServer/HttpServer.h"
#include "../ServerDataHelper/ServerData.h"
#include "../ParseServer/ParseServerImpl.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CWinHomeServerDlg dialog




CWinHomeServerDlg::CWinHomeServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CWinHomeServerDlg::IDD, pParent)
	, m_SharedFolder(_T(""))
	, m_IP(0)
	, m_URL(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CWinHomeServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_FOLDER, m_SharedFolder);
	DDX_IPAddress(pDX, IDC_IPADDRESS1, m_IP);
	DDX_Text(pDX, IDC_EDIT2, m_URL);
	DDX_Control(pDX, IDC_LIST_SHAREFOLDER, m_SharedFolderListCtrl);
}

BEGIN_MESSAGE_MAP(CWinHomeServerDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_BROWER, &CWinHomeServerDlg::OnBnClickedButtonBrower)
	ON_NOTIFY(NM_THEMECHANGED, IDC_IPADDRESS1, &CWinHomeServerDlg::OnNMThemeChangedIpaddress1)
	ON_BN_CLICKED(IDC_BUTTON_START, &CWinHomeServerDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDCANCEL, &CWinHomeServerDlg::OnBnClickedCancel)
END_MESSAGE_MAP()


// CWinHomeServerDlg message handlers

BOOL CWinHomeServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	//m_Config.LoadConfig();
	//m_IP = m_Config.m_IPAddress;
	//m_SharedFolder = m_Config.m_SharedFolder.c_str();
	//m_URL = m_Config.m_URLPath.c_str();
	UpdateData(FALSE);

	InitServer();

	IHomeServer * pHomeServer = CreateHomeServer();
	pHomeServer->StartServer();

	PrepareServerData();
	UpdateUIFromServerData();

/*
	typedef LRESULT (* _pfnLogIn)(LPCSTR lpUserName, LPCSTR lpPassword);
	typedef LRESULT (* _pfnLogOut)();
	typedef LRESULT (* _pfnSetIP)(LPCSTR lpEntryName, LPCSTR lpIPAddr);
	typedef LRESULT (* _pfnGetIP)(LPCSTR lpEntryName, LPSTR lpIPAddr);

	HINSTANCE hInstance = LoadLibrary(_T("GoogleProtocol.dll"));
	ASSERT(hInstance != NULL);

	_pfnLogIn  LogIn  = (_pfnLogIn)GetProcAddress(hInstance, "LogIn");
	_pfnLogOut LogOut = (_pfnLogOut)GetProcAddress(hInstance, "LogOut");
	_pfnGetIP  GetIP  = (_pfnGetIP)GetProcAddress(hInstance, "GetIP");
	_pfnSetIP  SetIP  = (_pfnSetIP)GetProcAddress(hInstance, "SetIP");


	LRESULT lResult = 0;

	//-------------------------------------------------------------------
	//  Description:      Login to google server.
	//
	//  Parameter:
	//      lpUserName:   User Account.
	//      lpPassword:   User Password.
	//
	//  Return:
	//       1            Succeed.
	//       0            Failed.
	//      -1            Http request error;
	//      -2            Authorization error.
	//      -3            Account Id or password error.
	//-------------------------------------------------------------------
	lResult = LogIn("username", "password");

	//-------------------------------------------------------------------
	//  Description:      Set server ip address to google contact.
	//
	//  Parameter:
	//      lpEntryName:  Server's name.
	//      lpIPAddr:     New server' ip address.
	//
	//  Return:
	//       2            Created succeed.
	//       1            Updated succeed.
	//       0            Failed.
	//      -1            Http request error;
	//      -2            Authorization error.
	//      -3            Account Id or password error.
	//-------------------------------------------------------------------
	lResult = SetIP("AcerMediaSync", "192.168.1.102");

	CHAR ip[128];

	//-------------------------------------------------------------------
	//  Description:      Get server ip address from google contact.
	//
	//  Parameter:
	//      lpEntryName:  Server's name.
	//      lpIPAddr:     Receives server' ip address.
	//
	//  Return:
	//       1            Succeed.
	//       0            Failed.
	//      -1            Http request error;
	//      -2            Authorization error.
	//      -3            Account Id or password error.
	//-------------------------------------------------------------------
	lResult = GetIP("AcerMediaSync", ip);

	//-------------------------------------------------------------------
	//  Description:     Logout from google server.
	//
	//  Parameter:
	//
	//  Return:
	//      1            Succeed.
	//      0            Failed.
	//-------------------------------------------------------------------
	lResult = LogOut();
*/

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CWinHomeServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CWinHomeServerDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CWinHomeServerDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

bool CWinHomeServerDlg::IsExist(wstring strFolder)
{
	int Count = m_SharedFolderListCtrl.GetItemCount();
	for( int i=0;i<Count;i++)
	{
		CString ItemText =m_SharedFolderListCtrl.GetItemText(i,0);
		if (ItemText.CompareNoCase(strFolder.c_str()) == 0)
			return true;
	}
	return false;
}
void CWinHomeServerDlg::OnBnClickedButtonBrower()
{
	// TODO: Add your control notification handler code here
	//CBrowseFolderDialog FileDialog(m_Config.m_ConfigPath.c_str(),0,this);
	//FileDialog.DoModal();

	//m_SharedFolder = FileDialog.GetPath();
	//UpdateData(FALSE);
	//SaveConfig();

	//if (!IsExist((LPCTSTR)m_SharedFolder))
	//	m_SharedFolderListCtrl.InsertItem(m_SharedFolderListCtrl.GetItemCount(),m_SharedFolder);
	//UpdateToServerData();
}

void CWinHomeServerDlg::OnNMThemeChangedIpaddress1(NMHDR *pNMHDR, LRESULT *pResult)
{
	// This feature requires Windows XP or greater.
	// The symbol _WIN32_WINNT must be >= 0x0501.
	// TODO: Add your control notification handler code here
	*pResult = 0;

	SaveConfig();
}
void CWinHomeServerDlg::SaveConfig()
{
	UpdateData(TRUE);
}

void CWinHomeServerDlg::PrepareServerData()
{
	//wstring dbPath = m_Config.m_ConfigPath.c_str();
	//dbPath += _T("ServerData.db");

	//InitServerData((TCHAR*)dbPath.c_str());

}
void CWinHomeServerDlg::UpdateToServerData()
{
	/*
	wstring dbPath = m_Config.m_ConfigPath.c_str();
	dbPath += _T("ServerData.db");

	InitServerData((TCHAR*)dbPath.c_str());

	int Count = m_SharedFolderListCtrl.GetItemCount();
	for(int i = 0; i<Count;i++)
	{
		AddShareFolder((TCHAR*)(LPCTSTR)m_SharedFolderListCtrl.GetItemText(i,0));
	}
	*/

}
void CWinHomeServerDlg::UpdateUIFromServerData()
{
	int Count = 0;

	for (int i=0;i<Count;i++)
	{
		SERVERDATA_SHAREDFOLDER FolderData;
		if (!IsExist((LPCTSTR)FolderData.szPath))
			m_SharedFolderListCtrl.InsertItem(m_SharedFolderListCtrl.GetItemCount(),FolderData.szPath);
	}

}

void CWinHomeServerDlg::OnBnClickedButtonStart()
{
	// TODO: Add your control notification handler code here
	SaveConfig();
	
	//StartHttpServer();
	//BindDllFunction("/Content","ParseServer.dll","ParseServerContent");
	//BindDllFunction("/Root","ParseServer.dll","ParseServerRoot");
	//BindDllFunction("/Thumbnail","ParseServer.dll","ParseThumbnail");
}

void CWinHomeServerDlg::OnBnClickedCancel()
{
	// TODO: Add your control notification handler code here
	OnCancel();
		
}

